package com.monitor.controller;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.github.abel533.echarts.Option;
import com.github.abel533.echarts.Title;
import com.github.abel533.echarts.code.Orient;
import com.github.abel533.echarts.code.Trigger;
import com.github.abel533.echarts.series.Pie;
import com.monitor.entity.*;
import com.monitor.service.*;
import com.monitor.util.BlankUtil;
import com.monitor.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.github.abel533.echarts.code.LegendType.scroll;

/**
 * <p>
 * 轮胎档案工作表 前端控制器
 * </p>
 *
 * @author LX
 * @since 2018-09-27
 */
@RestController
@RequestMapping("/erpTireArchivesWork")
@Api(description="统计管理-轮胎")
public class ErpTireArchivesWorkController {

    @Value("${web.upload-path}")
    private String path;
    @Resource
    private ErpManagementService managementService;
    @Resource
    private ErpUserService userService;
    @Resource
    private ErpMaterielFlowService materielFlowService;
    @Resource
    private ErpCustomerService customerService;
    @Resource
    private ErpCustomerCarService carService;
    @Resource
    private ErpMaterielFlowMaterielService flowMaterielService;
    @Resource
    private ErpMaterielFlowService flowService;
    @Resource
    private ErpMaterielService materielService;
    @Resource
    private ErpMaterielFlowSummaryService flowSummaryService;
    @Resource
    private ErpInspectionOrderService inspectionOrderService;
    @Resource
    private ErpInspectionContentService inspectionContentService;
    @Resource
    private ErpCustomerWarehouseService customerWarehouseService;
    @Resource
    private ErpCustomerCarService erpCustomerCarService;
    @Resource
    private ErpWarehouseService warehouseService;
    @Resource
    private ErpTireArchivesWorkService archivesWorkService;
    @Resource
    private ErpCarTireArchivesService carTireArchivesService;
    @Resource
    private ErpParametersService parametersService;
    @Resource
    private ErpSaleRepairOrderService repairOrderService;
    @Resource
    private ErpRefuelingService refuelingService;
    @Resource
    private ErpSaleRepairSaleService repairSaleService;
    @Resource
    private ErpSaleRepairRepairService repairRepairService;


    @RequestMapping("/tongjiguanliDetails")
    @ApiOperation("统计管理-查询车辆最近的两个检测维修单")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "catPlate", value = "车牌号", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<Map<String, Object>> tongjiguanliDetails(String catPlate) {
        Result<Map<String, Object>> result = new Result<Map<String, Object>>();
        try {
            Map<String, Object> map1 = new HashMap<String, Object>();
            ErpCustomerCar cars = carService.selectOne(new EntityWrapper<ErpCustomerCar>().eq("car_plate", catPlate));
            Integer contentId = inspectionContentService.getMaxIdContent(catPlate);
            List<ErpInspectionContent> inspectionContentList = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", catPlate).and().isNotNull("form_id").groupBy("form_id").orderBy("id"));
            if (0 == inspectionContentList.size()) {
                result.setCount(0);
                result.setData(null);
            } else {

                ErpInspectionOrder inspectionOrder = inspectionOrderService.selectOne(new EntityWrapper<ErpInspectionOrder>().eq("form_id", inspectionContentList.get(inspectionContentList.size() - 1).getFormId()));
                List<ErpInspectionContent> inspectionContentList1 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContentList.get(inspectionContentList.size() - 1).getFormId()));
                ErpManagement management = managementService.selectOne(new EntityWrapper<ErpManagement>().eq("work_id", inspectionContentList.get(inspectionContentList.size() - 1).getFormId()));

                map1.put("newDateContent", inspectionContentList1);
                map1.put("newDateOrder", inspectionOrder);
                map1.put("management", management);
                if (1 < inspectionContentList.size()) {
                    List<ErpInspectionContent> inspectionContentList2 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContentList.get(inspectionContentList.size() - 2).getFormId()));
                    map1.put("oldDateContent", inspectionContentList2);
                }
            }

            result.setCount(1);
            result.setData(map1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/tongjiguanliWLGX")
    @ApiOperation("统计管理-物料更新")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
    })
    public @ResponseBody
    Result<List<ErpMaterielFlow>> tongjiguanliWLGX(Integer custId, String startDate, String endDate) {
        Result<List<ErpMaterielFlow>> result = new Result<List<ErpMaterielFlow>>();
        try {

            String custIdsStr = customerService.getcustOfMe(custId);

            //List<ErpWarehouse> warehouseList=warehouseService.selectList(new EntityWrapper<ErpWarehouse>().in("customer_id",custIdsStr));
            List<ErpCustomerWarehouse> warehouseList = customerWarehouseService.selectList(new EntityWrapper<ErpCustomerWarehouse>().in("customer_id", custIdsStr));
            List<Integer> wareIds = warehouseList.stream().map(ErpCustomerWarehouse::getId).collect(Collectors.toList());
            String wareIdsStr = BlankUtil.listToString(wareIds);
            List<ErpMaterielFlow> flowList = flowService.selectList(new EntityWrapper<ErpMaterielFlow>().between(false, "materiel_flow_date", startDate, endDate).like("materiel_flow_sheet_id", "S").in("source_warehouse_id", wareIdsStr));//.or().in("warehouse_id",wareIdsStr).and().ge("materiel_flow_date",startDate).and().le("materiel_flow_date",endDate).like("materiel_flow_sheet_id","XSWX"));
            flowList.parallelStream().forEach(flow ->
                    {
                        List<ErpMaterielFlowSummary> flowSummaryList = flowSummaryService.selectList(new EntityWrapper<ErpMaterielFlowSummary>().in("warehouse_id", wareIdsStr).like("work_sheet_id", "XSWX"));
                        flow.setCustomerName(customerService.selectById(custId).getCusName());
                        flowSummaryList.parallelStream().forEach(flowSummary ->
                                {
                                    flowSummary.setFlowMateriel(flowMaterielService.selectById(flowSummary.getMaterielId()));
                                    ErpCustomerCar erpCustomerCar1 = erpCustomerCarService.selectOne(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId));

                                    flowSummary.setCarServiceCentre(erpCustomerCar1.getCarServiceCentre());
                                }

                        );
                        flow.setFlowSummaryList(flowSummaryList);
                    }

            );
//            for(ErpMaterielFlow flow:flowList){
////                List<ErpMaterielFlowSummary>  =flowSummaryService.selectList(new EntityWrapper<ErpMaterielFlowSummary>().in("warehouse_id",wareIdsStr));//.like("work_sheet_id","XSWX")
//                List<ErpMaterielFlowSummary> flowSummaryList = flowSummaryService.selectList(new EntityWrapper<ErpMaterielFlowSummary>().in("warehouse_id", wareIdsStr).like("work_sheet_id", "XSWX"));
//                for (ErpMaterielFlowSummary flowSummary:flowSummaryList) {
//                    /*ErpMaterielFlowMateriel flowMateriel=flowMaterielService.selectById(flowSummary.getMaterielId());
//                    Integer materielId=materielService.selectOne();*/
//                    flowSummary.setFlowMateriel(flowMaterielService.selectById(flowSummary.getMaterielId()));
//                    ErpCustomerCar erpCustomerCar1 = erpCustomerCarService.selectOne(new EntityWrapper<ErpCustomerCar>().eq("customer_id",custId));
//
//                    flowSummary.setCarServiceCentre(erpCustomerCar1.getCarServiceCentre());
//                }
////                System.out.println(wareIdsStr);
//                flow.setFlowSummaryList(flowSummaryList);
//            }
            result.setCount(1);
            result.setData(flowList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/tongjiguanliTWSD")
    @ApiOperation("统计管理-胎纹深度")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "catPlate", value = "车牌号", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<List<Map<String, Object>>> tongjiguanliTWSD(String catPlate, Integer custId, String startDate, String endDate) {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        try {
            List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
            List<ErpCustomerCar> cars = new ArrayList<ErpCustomerCar>();
            if (StringUtils.isEmpty(catPlate)) {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId));
            } else {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId).and().like("car_plate", catPlate));
            }
            for (int i = 0; i < cars.size(); i++) {
                Map<String, Object> map1 = new HashMap<String, Object>();
                Integer contentId = inspectionContentService.getMaxIdContentByPro(cars.get(i).getCarPlate(), startDate, endDate);
                map1.put("catPlate", cars.get(i).getCarPlate());
                map1.put("chelunzhoushju", cars.get(i).getCarWheel());
                map1.put("qudong", cars.get(i).getCarDrive());
                map1.put("luntaiguige", cars.get(i).getCarRims());
                map1.put("pinpai", cars.get(i).getCarBrand());
                map1.put("xinghao", cars.get(i).getCarModel());
                if (null == contentId || 0 == contentId) {
                    /*map1.put("mmone","");
                    map1.put("mmtwo","");
                    map1.put("mmthree","");
                    map1.put("mmfour","");
                    map1.put("jiancedate","");
                    map.add(map1);*/
                    continue;
                }

                ErpInspectionContent inspectionContent = inspectionContentService.selectById(contentId);
                Integer mmone = 0;
                Integer mmtwo = 0;
                Integer mmthree = 0;
                Integer mmfour = 0;
                if (null != inspectionContent) {
                    List<ErpInspectionContent> inspectionContentList = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContent.getFormId()));

                    for (ErpInspectionContent inspectionContent1 : inspectionContentList) {
                        Double shendu = inspectionContentService.getpinjuntaiwenshendu(inspectionContent1);
                        if (11.0 < shendu) {
                            mmone += 1;
                        }
                        if (11.0 >= shendu && shendu >= 5.0) {
                            mmtwo += 1;
                        }
                        if (5.0 > shendu && shendu >= 2.5) {
                            mmthree += 1;
                        }
                        if (2.5 > shendu) {
                            mmfour += 1;
                        }
                    }
                }

                map1.put("mmone", mmone);
                map1.put("mmtwo", mmtwo);
                map1.put("mmthree", mmthree);
                map1.put("mmfour", mmfour);
                Date currentTime = new Date();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = formatter.format(currentTime);
                map1.put("jiancedate", null != inspectionContent ? inspectionContent.getDt() : "");
                map.add(map1);
            }
            result.setCount(1);
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/tongjiguanliLTMH")
    @ApiOperation("统计管理-轮胎磨耗")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "catPlate", value = "车牌号", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<List<ErpCustomerCar>> tongjiguanliLTMH(String catPlate, Integer custId, String startDate, String endDate) {
        Result<List<ErpCustomerCar>> result = new Result<List<ErpCustomerCar>>();
        try {
            List<ErpCustomerCar> cars = new ArrayList<ErpCustomerCar>();
            if (StringUtils.isEmpty(catPlate)) {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId));
            } else {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId).and().like("car_plate", catPlate));
            }
            for (int i = 0; i < cars.size(); i++) {
                List<ErpInspectionContent> inspectionContents1 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", cars.get(i).getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).and().eq("tire_place", "右1轮").orderBy("id"));
                List<ErpInspectionContent> inspectionContents2 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", cars.get(i).getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).and().eq("tire_place", "右2轮").orderBy("id"));
                List<ErpInspectionContent> inspectionContents11 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", cars.get(i).getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).and().eq("tire_place", "左1轮").orderBy("id"));
                List<ErpInspectionContent> inspectionContents22 = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", cars.get(i).getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).and().eq("tire_place", "左2轮").orderBy("id"));
                List<ErpInspectionContent> inspectionContents = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", cars.get(i).getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).and().eq("tire_place", "备胎").orderBy("id"));
                cars.get(i).setYouOne(inspectionContentService.gettaiwenmohao(inspectionContents1));
                cars.get(i).setYouTwo(inspectionContentService.gettaiwenmohao(inspectionContents2));
                cars.get(i).setZuoOne(inspectionContentService.gettaiwenmohao(inspectionContents11));
                cars.get(i).setZuoTwo(inspectionContentService.gettaiwenmohao(inspectionContents22));
                cars.get(i).setBeitai(inspectionContentService.gettaiwenmohao(inspectionContents));
            }
            result.setCount(1);
            result.setData(cars);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/tongjiguanliLTZT")
    @ApiOperation("统计管理-轮胎状态")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "catPlate", value = "车牌号", required = false, dataType = "String", paramType = "query")
    })
    public @ResponseBody
    Result<List<Map<String, Object>>> tongjiguanliLTZT(String catPlate, Integer custId, String startDate, String endDate) {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        try {
            List<Map<String, Object>> map = new ArrayList<Map<String, Object>>();
            List<ErpCustomerCar> cars = new ArrayList<ErpCustomerCar>();
            if (StringUtils.isEmpty(catPlate)) {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId));
            } else {
                cars = carService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", custId).and().like("car_plate", catPlate));
            }
            for (int i = 0; i < cars.size(); i++) {
                Map<String, Object> map1 = new HashMap<String, Object>();
                Integer contentId = inspectionContentService.getMaxIdContentByPro(cars.get(i).getCarPlate(), startDate, endDate);

                map1.put("catPlate", cars.get(i).getCarPlate());
                map1.put("chelunzhoushju", cars.get(i).getCarWheel());
                map1.put("qudong", cars.get(i).getCarDrive());
                map1.put("luntaiguige", cars.get(i).getCarRims());
                map1.put("pinpai", cars.get(i).getCarBrand());
                map1.put("xinghao", cars.get(i).getCarModel());
                if (null == contentId || 0 == contentId) {
                    map1.put("pingmo", "");
                    map1.put("pianmo", "");
                    map1.put("kentai", "");
                    map1.put("posun", "");
                    map1.put("jiancedate", "");
                    map.add(map1);
                    continue;
                }

                ErpInspectionContent inspectionContent = inspectionContentService.selectById(contentId);
                if (null == inspectionContent) {
                    map1.put("pingmo", 0);
                    map1.put("pianmo", 0);
                    map1.put("kentai", 0);
                    map1.put("posun", 0);
                    map1.put("jiancedate", "");
                    map.add(map1);
                }
                Integer pingmoCount = inspectionContentService.selectCount(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContent.getFormId()).and().eq("tire_status", "平磨"));
                Integer pianmoCount = inspectionContentService.selectCount(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContent.getFormId()).and().eq("tire_status", "偏磨"));
                Integer kentaiCount = inspectionContentService.selectCount(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContent.getFormId()).and().eq("tire_status", "啃胎"));
                Integer posunCount = inspectionContentService.selectCount(new EntityWrapper<ErpInspectionContent>().eq("form_id", inspectionContent.getFormId()).and().eq("tire_status", "破损"));
                map1.put("pingmo", pingmoCount);
                map1.put("pianmo", pianmoCount);
                map1.put("kentai", kentaiCount);
                map1.put("posun", posunCount);
                map1.put("jiancedate", inspectionContent.getDt());
                map.add(map1);
            }
            result.setCount(1);
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/getTireState")
    @ApiOperation("统计管理-轮胎统计")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = false, dataType = "int", paramType = "query"),*/
            @ApiImplicitParam(name = "state", value = "1:全部轮胎2:在车轮胎3:库存轮胎4:报废轮胎", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户ID", required = false, dataType = "int", paramType = "query")
    })
    public @ResponseBody
    Result<List<Map<String, Object>>> getTireState(Integer custId, @RequestParam(value = "state", defaultValue = "1") Integer state) {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        try {
            ErpCustomerWarehouse customerWarehouse = customerWarehouseService.selectOne(new EntityWrapper<ErpCustomerWarehouse>().eq("customer_id", custId));
            if (null == customerWarehouse) {
                result.setCount(0);
                result.setData(null);
                return result;
            }

            List<ErpWarehouse> warehouseList = warehouseService.selectList(new EntityWrapper<ErpWarehouse>().eq("customer_id", custId));
            if (null == warehouseList) {
                result.setCount(0);
                result.setData(null);
                return result;
            }
            List<ErpMateriel> materiels = null;
            boolean a;
            if (state == 1) {
                materiels = materielService.selectList(new EntityWrapper<ErpMateriel>().eq("warehouse_id", customerWarehouse.getId()));
            } else {
                materiels = materielService.selectList(new EntityWrapper<ErpMateriel>().eq("warehouse_id", customerWarehouse.getId()).eq("state", state));
            }
//             materiels=materielService.selectList(new EntityWrapper<ErpMateriel>().eq("warehouse_id",customerWarehouse.getId()));


            if (0 == materiels.size()) {
                result.setCount(0);
                result.setData(null);
                return result;
            }
            for (ErpMateriel materiel : materiels) {
                Map<String, Object> map = new HashMap<String, Object>();
                ErpMaterielFlowMateriel flowMateriel = flowMaterielService.selectById(materiel.getMaterielId());
                materiel.setMaterielFlowMateriel(null == flowMateriel ? null : flowMateriel);
                ErpCarTireArchives carTireArchives = carTireArchivesService.selectOne(new EntityWrapper<ErpCarTireArchives>().eq("tire_id", materiel.getId()));
                if (null != carTireArchives) {
                    map.put("carTireArchives", carTireArchives);
                } else {
                    continue;
                }
                List<ErpTireArchivesWork> tireWorkList = archivesWorkService.selectList(new EntityWrapper<ErpTireArchivesWork>().eq("tire_id", materiel.getId()));
                double mileage = 0.0, mileagenew = 0.0, mileage1 = 0.0, mileage2 = 0.0, mileage3 = 0.0;
                double price = 0.0, priceNew = 0.0, price1 = 0.0, price2 = 0.0, price3 = 0.0, maxprice = 0.0;
                double priceRepair = 0.0, priceRepairNew = 0.0, priceRepair1 = 0.0, priceRepair2 = 0.0, priceRepair3 = 0.0;
                double logmileage = 0.0;
                double lines = 0.0;
                for (ErpTireArchivesWork taw : tireWorkList) {
                    if (taw.getCalculatingMileage() == 1) {
                        mileage += (taw.getWorkMileage() - logmileage);
                        if (taw.getTireState().equals("新物品") || taw.getTireState().equals("旧物品")) {
                            mileagenew += (taw.getWorkMileage() - logmileage);
                        } else if (taw.getTireState().equals("翻新1")) {
                            mileage1 += (taw.getWorkMileage() - logmileage);
                        } else if (taw.getTireState().equals("翻新2")) {
                            mileage2 += (taw.getWorkMileage() - logmileage);
                        } else if (taw.getTireState().equals("翻新3")) {
                            mileage3 += (taw.getWorkMileage() - logmileage);
                        }
                    }
                    logmileage = taw.getWorkMileage();
                    if (taw.getCostType() == 0 && taw.getTireCost() > maxprice) {
                        maxprice = taw.getTireCost();
                    }

                    if (taw.getCostType() == 1) {
                        priceRepair += taw.getTireCost();
                        if (taw.getTireState().equals("新物品") || taw.getTireState().equals("旧物品")) {
                            priceRepairNew += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新1")) {
                            priceRepair1 += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新2")) {
                            priceRepair2 += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新3")) {
                            priceRepair3 += taw.getTireCost();
                        }
                    }

                    if (taw.getCostType() == 2) {
                        price += taw.getTireCost();
                        if (taw.getTireState().equals("新物品") || taw.getTireState().equals("旧物品")) {
                            priceNew += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新1")) {
                            price1 += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新2")) {
                            price2 += taw.getTireCost();
                        } else if (taw.getTireState().equals("翻新3")) {
                            price3 += taw.getTireCost();
                        }
                    }

                }
                /*hql = "select p.linesS from ErpParameters p where p.arand=? and p.norms=? and p.model=? and p.address=?";
				String linesS = (String) dao.findOne(hql, materiel.getMaterielBrand(),
						materiel.getMaterielSpecifications(), materiel.getMaterielModel(),
						materiel.getMaterielPlace());*/
                ErpParameters parameters = parametersService.selectOne(new EntityWrapper<ErpParameters>().eq("arand", materiel.getMaterielBrand()).and().eq("norms", materiel.getMaterielSpecifications()).and().eq("model", materiel.getMaterielModel()).and().eq("address", materiel.getMaterielPlace()));
                if (null != parameters) {
                    map.put("parameters", parameters);
                }


                price += maxprice;
                priceNew += maxprice;
                price1 += maxprice;
                price2 += maxprice;
                price3 += maxprice;
                map.put("price", price);
                map.put("priceNew", priceNew);
                map.put("price1", price1);
                map.put("price2", price2);
                map.put("price3", price3);
                map.put("materiel", materiel);
                mapList.add(map);
            }
            result.setCount(0);
            result.setData(mapList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    @RequestMapping("/tongjiguanliYYTJ")
    @ApiOperation("统计管理-运营统计")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
    })
    public @ResponseBody
    Result<List<Map<String, Object>>> tongjiguanliYYTJ(Integer custId, String startDate, String endDate) {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            ErpCustomer customer = customerService.selectById(custId);
            List<ErpCustomer> erpCustomerList = customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_service_com", customer.getCusCode()));
            erpCustomerList.add(customer);
            erpCustomerList.parallelStream().forEach(cust -> {
                List<ErpCustomer> customers = customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_sup_company", cust.getCusCode()).or().eq("cus_service_com", cust.getCusCode()));
                customers.add(0, cust);
                //for(ErpCustomer customer1:customers){
                customers.parallelStream().forEach(customer1 -> {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Double mileage = 0.0;//运营里程
                    Double qitashouru = 0.0;//其他收入
                    Double qitazhichu = 0.0;//其他支出
                    List<ErpCustomerCar> customerCarList = erpCustomerCarService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", customer1.getId()));
                    for (ErpCustomerCar customerCar : customerCarList) {
                        List<ErpInspectionContent> contents = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", customerCar.getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).orderBy("dt", false));
                        if (0 < contents.size()) {
                            String formIdEnd = contents.get(0).getFormId();
                            String formIdStart = contents.get(contents.size() - 1).getFormId();
                            ErpInspectionOrder orderend = inspectionOrderService.selectOne(new EntityWrapper<ErpInspectionOrder>().eq("form_id", formIdEnd));
                            ErpInspectionOrder orderStart = inspectionOrderService.selectOne(new EntityWrapper<ErpInspectionOrder>().eq("form_id", formIdStart));
                            mileage += orderend.getMileage() - orderStart.getMileage();
                        }
                    }
                    List<ErpManagement> managementList = managementService.selectList(new EntityWrapper<ErpManagement>().eq("customer_id", customer1.getId()).ge("dt", startDate).le("dt", endDate));
                    map.put("id", customer1.getId());
                    map.put("qitashouru", qitashouru);
                    map.put("qitazhichu", qitazhichu);
                    map.put("carAllNum", customerCarList.size());//车辆总数
                    map.put("carRefueling", refuelingService.getRefuleMoneySum(customer1.getId()));//燃油支出
                    map.put("yunyingshuliang", erpCustomerCarService.selectCount(new EntityWrapper<ErpCustomerCar>().eq("customer_id", customer1.getId()).eq("car_operation_type", "启用")));//运营数量customerCarList.stream().filter(car->!StringUtils.isEmpty(car.getCarOperateType()))
                    map.put("customerName", customer1.getCusName());//客户名称
                    map.put("mileage", mileage);//运营里程
                    map.put("caigouzhichu", managementList.stream().filter(management -> management.getPurchase() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//采购支出
                    map.put("xiaoshoushouru", managementList.stream().filter(management -> management.getPurchase() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//销售收入
                    map.put("repairzhichu", managementList.stream().filter(management -> management.getErpRepair() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维修支出
                    map.put("repairshouru", managementList.stream().filter(management -> management.getErpRepair() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维修收入
                    map.put("maintianzhichu", managementList.stream().filter(management -> management.getMaintian() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维护支出
                    map.put("maintianshouru", managementList.stream().filter(management -> management.getMaintian() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维护收入
                    map.put("cashzhichu", managementList.stream().filter(management -> management.getCash() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维护支出
                    map.put("cashshouru", managementList.stream().filter(management -> management.getCash() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维护收入
                    list.add(map);
                });
            });
            result.setCount(list.size());
            result.setData(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/tongjiguanliYYTJBing")
    @ApiOperation("统计管理-运营统计饼图")
    @ApiImplicitParams({
           /* @ApiImplicitParam(name = "id", value = "id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "部门名称", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),*/
            @ApiImplicitParam(name = "startDate", value = "开始时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endDate", value = "结束时间", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "custId", value = "客户Id", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "1是经营收入,2是费用支出,3是运营利润,4是运营里程", required = false, dataType = "int", paramType = "query"),

    })
    public @ResponseBody
    String tongjiguanliYYTJBing(Integer custId, String startDate, String endDate, Integer type) {
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        String strings="";
        try {
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
            ErpCustomer customer = customerService.selectById(custId);
            List<ErpCustomer> erpCustomerList = customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_service_com", customer.getCusCode()));
            erpCustomerList.add(customer);
            erpCustomerList.parallelStream().forEach(cust -> {
                List<ErpCustomer> customers = customerService.selectList(new EntityWrapper<ErpCustomer>().eq("cus_sup_company", cust.getCusCode()).or().eq("cus_service_com", cust.getCusCode()));
                customers.add(0, cust);
                //for(ErpCustomer customer1:customers){
                customers.parallelStream().forEach(customer1 -> {
                    Map<String, Object> map = new HashMap<String, Object>();
                    Double mileage = 0.0;//运营里程
                    Double qitashouru = 0.0;//其他收入
                    Double qitazhichu = 0.0;//其他支出
                    List<ErpCustomerCar> customerCarList = erpCustomerCarService.selectList(new EntityWrapper<ErpCustomerCar>().eq("customer_id", customer1.getId()));
                    for (ErpCustomerCar customerCar : customerCarList) {
                        List<ErpInspectionContent> contents = inspectionContentService.selectList(new EntityWrapper<ErpInspectionContent>().eq("customer_id", customerCar.getCarPlate()).and().ge("dt", startDate).and().le("dt", endDate).orderBy("dt", false));
                        if (0 < contents.size()) {
                            String formIdEnd = contents.get(0).getFormId();
                            String formIdStart = contents.get(contents.size() - 1).getFormId();
                            ErpInspectionOrder orderend = inspectionOrderService.selectOne(new EntityWrapper<ErpInspectionOrder>().eq("form_id", formIdEnd));
                            ErpInspectionOrder orderStart = inspectionOrderService.selectOne(new EntityWrapper<ErpInspectionOrder>().eq("form_id", formIdStart));
                            mileage += orderend.getMileage() - orderStart.getMileage();
                        }
                    }
                    List<ErpManagement> managementList = managementService.selectList(new EntityWrapper<ErpManagement>().eq("customer_id", customer1.getId()).ge("dt", startDate).le("dt", endDate));
                    map.put("id", customer1.getId());
                    map.put("qitashouru", qitashouru);
                    map.put("qitazhichu", qitazhichu);
                    map.put("carAllNum", customerCarList.size());//车辆总数
                    map.put("carRefueling", refuelingService.getRefuleMoneySum(customer1.getId()));//燃油支出
                    map.put("yunyingshuliang", erpCustomerCarService.selectCount(new EntityWrapper<ErpCustomerCar>().eq("customer_id", customer1.getId()).eq("car_operation_type", "启用")));//运营数量customerCarList.stream().filter(car->!StringUtils.isEmpty(car.getCarOperateType()))
                    map.put("customerName", customer1.getCusName());//客户名称
                    map.put("mileage", mileage);//运营里程
                    map.put("caigouzhichu", managementList.stream().filter(management -> management.getPurchase() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//采购支出
                    map.put("xiaoshoushouru", managementList.stream().filter(management -> management.getPurchase() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//销售收入
                    map.put("repairzhichu", managementList.stream().filter(management -> management.getErpRepair() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维修支出
                    map.put("repairshouru", managementList.stream().filter(management -> management.getErpRepair() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维修收入
                    map.put("maintianzhichu", managementList.stream().filter(management -> management.getMaintian() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维护支出
                    map.put("maintianshouru", managementList.stream().filter(management -> management.getMaintian() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维护收入
                    map.put("cashzhichu", managementList.stream().filter(management -> management.getCash() > 0 && management.getCope() > 0).mapToDouble(ErpManagement::getCope).sum());//维护支出
                    map.put("cashshouru", managementList.stream().filter(management -> management.getCash() > 0 && management.getAccounts() > 0).mapToDouble(ErpManagement::getAccounts).sum());//维护收入
                    list.add(map);
                });
            });

            List<Map<String, Object>> map = new ArrayList<>();
            String[] searchs = null;
            Option op = new Option();
            if (type == 1) {
                op.setTitle(new Title().text("经营收入饼图"));


                    for (int i = 0; i < list.size(); i++) {
                        Map<String, Object> s =  list.get(i);
                    Map<String, Object> aa = new HashMap<>();
                    aa.put("name", String.valueOf(s.get("customerName")));
                    aa.put("value", Double.valueOf(String.valueOf(s.get("xiaoshoushouru"))) + Double.valueOf(String.valueOf(s.get("qitashouru")))
                            + Double.valueOf(String.valueOf(s.get("maintianshouru"))) +
                            Double.valueOf(String.valueOf(s.get("cashshouru"))));
                    map.add(aa);
                    }


            } else if (type == 2) {
                op.setTitle(new Title().text("费用支出饼图"));
                for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> s =  list.get(i);
                    Map<String, Object> aa = new HashMap<>();
                    aa.put("name", String.valueOf(s.get("customerName")));
                    aa.put("value", Double.valueOf(String.valueOf(s.get("qitazhichu"))) + Double.valueOf(String.valueOf(s.get("repairzhichu")))
                            + Double.valueOf(String.valueOf(s.get("caigouzhichu"))) + Double.valueOf(String.valueOf(s.get("maintianzhichu"))) +
                            Double.valueOf(String.valueOf(s.get("cashzhichu"))));
                    map.add(aa);
                }
            } else if (type == 3) {
                op.setTitle(new Title().text("运营利润饼图"));
                for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> s =  list.get(i);
                    Map<String, Object> aa = new HashMap<>();
                    aa.put("name", String.valueOf(s.get("customerName")));
                    aa.put("value", (Double.valueOf(String.valueOf(s.get("xiaoshoushouru"))) + Double.valueOf(String.valueOf(s.get("qitashouru")))
                            + Double.valueOf(String.valueOf(s.get("maintianshouru"))) +
                            Double.valueOf(String.valueOf(s.get("cashshouru")))) - (Double.valueOf(String.valueOf(s.get("qitazhichu"))) + Double.valueOf(String.valueOf(s.get("repairzhichu")))
                            + Double.valueOf(String.valueOf(s.get("caigouzhichu"))) + Double.valueOf(String.valueOf(s.get("maintianzhichu"))) +
                            Double.valueOf(String.valueOf(s.get("cashzhichu")))));
                    map.add(aa);
                }
            }else {
                op.setTitle(new Title().text("运营里程饼图"));
                for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> s =  list.get(i);
                    Map<String, Object> aa = new HashMap<>();
                    aa.put("name", String.valueOf(s.get("customerName")));
                    aa.put("value", Double.valueOf(String.valueOf(s.get("yunyingshuliang"))) + Double.valueOf(String.valueOf(s.get("mileage")))
                            + Double.valueOf(String.valueOf(s.get("carAllNum")

                            )));
                    map.add(aa);
                }
            }
            List<Double> count = new ArrayList<>();
            List<String> Type = new ArrayList<>();
            for (int i = 0; i < map.size(); i++) {
                Map<String,Object> m=map.get(i);
                if (m!=null){


                Type.add(String.valueOf(m.get("name")));
                count.add(Double.valueOf(String.valueOf(m.get("value"))));
                }

            }
//                map.parallelStream().forEach(m->{
//
//                    Type.add(String.valueOf(m.get("name")));
//                    count.add(Double.valueOf(m.get("value").toString()));
//                });


            Double[] d = new Double[count.size()];
            for (int i = 0; i < count.size(); i++) {
                d[i] = count.get(i);
            }

            searchs = Type.toArray(new String[Type.size()]);
            op.tooltip(Trigger.item);
            op.tooltip().formatter("{a} <br/>{b} : {c} ({d}%)");
            op.legend().data(searchs).type(scroll).orient(Orient.vertical).right(10).top(20).bottom(20);
            //.selected()缺个这个
            //for(String po:CarTypeEnum.CARTYPE7.getPosition()) {
            Pie pie = new Pie();//创建饼图对象
            pie.name("数据").radius("55%").center("40%", "50%").itemStyle().emphasis().shadowBlur(10).shadowOffsetX(0).shadowColor("'rgba(0, 0, 0, 0.5)'");
            //填充数据
            for (int i = 0; i < searchs.length; i++) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("value", d[i]);//填充饼图数据
                map1.put("name", searchs[i]);//填充饼图数据对应的搜索引擎
                pie.data(map1);
            }
            pie.data(map);
            op.series(pie);
            strings = JSON.toJSONStringWithDateFormat(op, "yyyy-MM-dd HH:mm:ss", SerializerFeature.DisableCircularReferenceDetect);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return strings;
    }




}

